#include <cs50.h>
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <string.h>

int count_letters(string text);
int count_words(string text);
int count_sentences(string text);

int main(void)
{
    string text = get_string("Text: ");
    int letters = count_letters(text);
    int words = count_words(text);
    int sentences = count_sentences(text);

    // printf("%d letters\n",letters);
    // printf("%d words\n",words);
    // printf("%d sentences\n",sentences);

    float L = (float) letters / (float) words * 100;
    float S = (float) sentences / (float) words * 100;
    int index = round(0.0588 * L - 0.296 * S - 15.8);

    if (index < 1)
    {
        printf("Before Grade 1\n");
    }
    else if (index >= 16)
    {
        printf("Grade 16+\n");
    }
    else
    {
        printf("Grade %d\n", index);
    }
}

// 计算字母数量部分
int count_letters(string text)
{

    int letters = 0;

    for (int i = 0; text[i] != '\0'; i++)
    {

        if (isalpha(text[i]))
        {
            letters++;
        }
    }
    return letters;
}

// 计算单词数量部分
int count_words(string text)
{
    int words = 0;

    for (int i = 0; text[i] != '\0'; i++)
    {
        if (isspace(text[i]))
        {
            words++;
        }
    }

    return words + 1;
}

// 计算句子数量部分
int count_sentences(string text)
{
    int sentences = 0;

    for (int i = 0; text[i] != '\0'; i++)
    {
        switch (text[i])
        {
            case '.':
                sentences++;
                break;

            case '!':
                sentences++;
                break;

            case '?':
                sentences++;
                break;
        }
    }
    return sentences;
}
